<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/10
 * Time: 17:26
 */

namespace App\Services;

use App\Models\Admin;
use App\Models\Task;

class TaskService extends BaseService
{
    protected $modelClass = Task::class;

    /**
     * 添加
     * @param $postData
     * @return bool|string
     * @throws \Exception
     */
    public function add($postData)
    {
        return $this->saveData($postData);
    }

    /**
     * 编辑
     * @param $id
     * @param $postData
     * @return mixed
     * @throws \Exception
     */
    public function edit($id, $postData)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->update(filter_null($postData))) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 详情
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function detail($id)
    {
        try {
            $obj = $this->model
                ->where('id', $id)
                ->with(['attach', 'finishAttach', 'assignUser', 'log'])
                ->first();

            if (!$obj) {
                throw new \Exception('未找到！');
            }

            return $obj;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function remove($id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process == '进行中') {
                throw new \Exception('不能删除进行中的任务！');
            }

            return $obj->update(['is_enable' => 0]);
        } catch (\Exception $e) {
            throw new \Exception('删除失败！');
        }
    }

    /**
     * @param $id
     * @param $postData
     * @return mixed
     * @throws \Exception
     */
    public function assign($id, $postData)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if (!in_array($obj->process, ['未指派', '已取消'])) {
                throw new \Exception('只能指派未指派或已取消的任务！');
            }

            $user = Admin::query()->where('admin_id', $postData['user_id'])
                ->where('user_type', 2)->first();

            if ($obj->update([
                'process' => '待开始',
                'user_id' => $user->admin_id,
                'username' => $user->username,
                'assigned_at' => date('Y-m-d H:i:s'),
            ])) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function cancel($id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '待开始') {
                throw new \Exception('只能取消待开始状态的任务！');
            }

            return $obj->update([
                'process' => '已取消',
                'user_id' => 0,
                'username' => '',
                'assigned_at' => null,
            ]);
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @param $id
     * @param $user_id
     * @return bool|mixed
     * @throws \Exception
     */
    public function start($id, $user_id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '待开始') {
                throw new \Exception('只能开始待开始的任务！');
            }

            if ($obj->user_id != $user_id) {
                throw new \Exception('只能开始自己的任务！');
            }

            if ($obj->update([
                'process' => '进行中',
            ])) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @param $id
     * @param $user_id
     * @return bool|mixed
     * @throws \Exception
     */
    public function finish($id, $user_id, $postData)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '进行中') {
                throw new \Exception('只能完成进行中的任务！');
            }

            if ($obj->user_id != $user_id) {
                throw new \Exception('只能完成自己的任务！');
            }

            if ($obj->update([
                'process' => '已完成',
                'finish_attach_id' => $postData['finish_attach_id'],
                'finished_at' => date('Y-m-d H:i:s')
            ])) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @desc 列表
     * @param array $search
     * @param int $per_page
     * @return array
     */
    public function getList($search=[], $per_page=20)
    {
        $res = $this->model->with(['attach', 'finishAttach', 'assignUser', 'log']);

        if (!empty($search['user_id'])) {
            $res = $res->where('user_id', $search['user_id']);
        }

        if (!empty($search['filename'])) {
            $res = $res->where('filename', 'like', "%{$search['filename']}%");
        }

        if (!empty($search['username'])) {
            $res = $res->where('username', 'like', "%{$search['username']}%");
        }

        if (!empty($search['importance'])) {
            $res = $res->where('importance', $search['importance']);
        }

        if (!empty($search['process'])) {
            $res = $res->where('process', $search['process']);
        }

        if (!empty($search['assignDate'])) {
            $res = $res->whereBetween('assigned_at', $search['assignDate']);
        }

        if (!empty($search['type'])) {
            $res = $res->whereHas('attach', function($query)use($search){
                $query->where('suffix', $search['type']);
            });
        }

        if (!empty($search['sort'])) {
            if ($search['sort'] == '-id') {
                $res = $res->orderBy('id', 'desc');
            } else {
                $res = $res->orderBy('id', 'asc');
            }
        }

        return $this->get_paginate($res->paginate($per_page, ['*']));
    }

    public function info()
    {
        $res = [
            'all' => 0,
            'finish' => 0,
            'unAssign'=> 0,
            'processing' => 0,
        ];

        $obj = $this->getAll(['process']);
        foreach ($obj as $o) {
            if ($o->process == '已完成') {
                $res['finish'] ++;
            }
            if ($o->process == '未指派') {
                $res['unAssign'] ++;
            }
            if ($o->process == '进行中') {
                $res['processing'] ++;
            }

            $res['all'] ++;
        }

        return $res;
    }

}